package se.energimyndigheten.lampguiden.bulbreplacement;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.accessibility.AccessibilityEvent;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONException;

import se.energimyndigheten.lampguiden.R;
import se.energimyndigheten.lampguiden.LightSource;
import se.energimyndigheten.lampguiden.SubPageActivity;
import se.energimyndigheten.lampguiden.util.AssetsUtil;

import java.io.IOException;
import java.util.Map;

public class PowerActivity extends SubPageActivity implements SeekBar.OnSeekBarChangeListener {

    public static final String KEY_POWER = "POWER";

    private static final String TAG = PowerActivity.class.getSimpleName();
    private static final String HELP_PATH = HTML_BASEPATH + "Help/sv_Power.html";

    private SeekBar mSeekBar;
    private ImageView mLightBulb;
    private ImageView mBulbWire;
    private ImageView mBulbGlow;
    private ImageView mBulbRadiance;
    private ImageView mBulbGlare;
    private TextView mNextHint;
    private TextView mWattLabel;
    private TextView mLumenLabel;
    private int mPowerIndex;
    private int mProgressSteps;
    private int mSocketType;
    private int[] mEffects;
    private LightSource mLightSource;
    private Map<Integer, String> mLumenTable;
    private int maxVal;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        Log.v(TAG, "onCreate");
        super.onCreate(savedInstanceState);

        // grab socket type from intent and parse lightsource from json
        try {
            mSocketType = getIntent().getIntExtra(SocketActivity.KEY_SOCKET, -1);
            Log.v(TAG, " - socket: " + mSocketType);
            String json = AssetsUtil.getFileContents(getAssets(), AssetsUtil.JSON_PATH_LIGHTSOURCE);
            mLightSource = AssetsUtil.getLightSourceFromJson(json, mSocketType);
            mEffects = mLightSource.getEffects(); // to avoid getting evertime on seekbar change
            maxVal = mEffects[mEffects.length-1];
            mLumenTable = AssetsUtil.getConversionTableFromJson(json, mLightSource.getLampType());
        } catch (NullPointerException npE) {
            Log.e(TAG, "Invalid or missing intent. Expected intent with string extra: " + SocketActivity.KEY_SOCKET);
            mSocketType = -1;
        } catch (JSONException jsonE) {
            Log.e(TAG, "JSONException parsing JSON");
            jsonE.printStackTrace();
            mSocketType = -1;
        } catch (IOException ioE) {
            Log.e(TAG, "IOException reading JSON");
            ioE.printStackTrace();
            mSocketType = -1;
        } finally {
            if (mSocketType == -1) {
                // fail - bail
                finish();
                return;
            }
        }

        setContentView(R.layout.power_activity);
        initView();
    }

    @SuppressWarnings("deprecation")
    private void initView() {

        mWattLabel = (TextView) findViewById(R.id.power_watt);
        mLumenLabel = (TextView) findViewById(R.id.power_lumen);
        mLightBulb = (ImageView) findViewById(R.id.bulb);
        mBulbWire = (ImageView) findViewById(R.id.bulb_wire);
        mBulbGlow = (ImageView) findViewById(R.id.bulb_radiance);
        mBulbRadiance = (ImageView) findViewById(R.id.bulb_radiance2);
        mBulbGlare = (ImageView) findViewById(R.id.bulb_glare);
        mNextHint = (TextView) findViewById(R.id.next_hint);
        mNextHint.setVisibility(View.GONE);

        mSeekBar = (SeekBar) findViewById(R.id.seekbar);
        mSeekBar.setMax(255);
        mSeekBar.setOnSeekBarChangeListener(this);
        mSeekBar.requestFocus(); // Try to get focus

        mProgressSteps = (int) Math.floor(mSeekBar.getMax() / (mLightSource.getEffects().length - 1));

        // lights off
        mBulbWire.setAlpha(0);
        mBulbGlare.setAlpha(0);
        mBulbGlow.setAlpha(0);
        mBulbRadiance.setAlpha(0);

        // set drawables
        int[] images = mLightSource.getImages();
        mLightBulb.setImageResource(images[LightSource.IMAGE_BASE]);
        if (images[LightSource.IMAGE_WIRE] > 0) {
            mBulbWire.setImageResource(images[LightSource.IMAGE_WIRE]);
        } else {
            mBulbWire.setVisibility(View.GONE);
        }
        if (images[LightSource.IMAGE_GLOW] > 0) {
            mBulbGlow.setImageResource(images[LightSource.IMAGE_GLOW]);
        } else {
            mBulbGlow.setVisibility(View.GONE);
        }
        if (images[LightSource.IMAGE_RADIANCE] > 0) {
            mBulbRadiance.setImageResource(images[LightSource.IMAGE_RADIANCE]);
        } else {
            mBulbRadiance.setVisibility(View.GONE);
        }

        // Initiate calculations with minimum
        mSeekBar.setProgress(mEffects[0] * 255 / maxVal);
//        onProgressChanged(mSeekBar, 0, true); 
    }

    @Override
    protected void onResume() {
        mSelectedActivity = ACTIVITY_SOCKET;
        super.showHelpActionItem(HELP_PATH);
        super.onResume();
        showNextHint();
    }

    /** Onclick event handler from layout xml. */
    public void onContinueClick(View view) {
        // only respond if power-slider has been altered
        if (mPowerIndex < 0) {
            Toast.makeText(this, R.string.power_please_select, Toast.LENGTH_LONG).show();
            return;
        }

        Intent intent = new Intent(this, ResultActivity.class);
        intent.putExtra(KEY_POWER, mPowerIndex);
        intent.putExtra(SocketActivity.KEY_SOCKET, mSocketType);
        startActivity(intent);
    }

    /** Seekbar event tracker */
    @SuppressWarnings("deprecation")
    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        // minimum alpha is first step or light will be out
        final int alpha = progress;
//        final int steps = (int) Math.floor(progress / mProgressSteps);
        progress = progress * maxVal / 255;
        
        Log.v(TAG, " - Progress: " + progress + " alpha: " + alpha); // + " steps: " + steps);

        try { 

            mBulbWire.setAlpha(progress < 120 ? alpha * 2 : 255);
            mBulbGlow.setAlpha(alpha);

            // double radiance = (8 * Math.pow(2d, progress / 51d));
            // Log.v(TAG, "rad - " + radiance);
            // mBulbRadiance.setAlpha((int) radiance - 1);
            mBulbRadiance.setAlpha(progress/2+127);

            // add glare if more than 128
//            mBulbGlare.setAlpha(progress > 128 ? 2 * (progress - 128) : 0);

            int n = mEffects.length;
            int max = mEffects[n-1];
            int val = progress;
            mPowerIndex = mEffects[n-1];
            int steps=n-1;
            for(int i = 0; i < n; i++) {
                if (progress <= mEffects[i]) {
                    mPowerIndex=mEffects[i];
                    steps=i;
                    break;
                }
            }
            
//            mPowerIndex = mEffects[steps];
            
            mWattLabel.setText(getResources().getString(R.string.power_watt_label, mEffects[steps]));
            mWattLabel.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED);
            String lbl =  mLumenTable.get(mPowerIndex).replace( ",", " - ");
            mLumenLabel.setText(getResources().getString(R.string.power_lumen_equiv_label, lbl));
            mLumenLabel.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED);
            seekBar.setContentDescription(mWattLabel.getText()+" "+mLumenLabel.getText());
            seekBar.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
            Log.v(TAG, " - Progress: result=" + mPowerIndex);
        } catch (ArrayIndexOutOfBoundsException aiooe) {
            Log.e(TAG, " - OutOfBounds! :: Progress: " + progress);
        }
        showNextHint();
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
        mNextHint.clearAnimation();
        mNextHint.setVisibility(View.GONE);
    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        Log.v(TAG, "onStopTrackingTouch "+mPowerIndex);
        seekBar.setProgress(mPowerIndex*255/maxVal);
    }

    private void showNextHint() {
        final Animation fadeIn = new AlphaAnimation(0.0f, 1.0f);
        fadeIn.setDuration(500);
        fadeIn.setStartOffset(3000);

        final Animation fadeOut = new AlphaAnimation(1.0f, 0.0f);
        fadeOut.setDuration(500);
        fadeOut.setStartOffset(3000);

        fadeIn.setAnimationListener(new AnimationListener() {

            @Override
            public void onAnimationStart(Animation animation) {
                mNextHint.setVisibility(View.VISIBLE);

            }

            @Override
            public void onAnimationRepeat(Animation animation) {
                // do nothing

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                // launch fade out
//                mNextHint.startAnimation(fadeOut);
            }
        });

        fadeOut.setAnimationListener(new AnimationListener() {

            @Override
            public void onAnimationStart(Animation animation) {
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
//                mNextHint.startAnimation(fadeIn);

            }
        });

        mNextHint.startAnimation(fadeIn);
    }

}
